﻿using Business.Service;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace MvcAppWeb.Controllers
{
    public class OffShelvesController : BaseDataController
    {
        //
        // GET: /LocationInfo/

        public ActionResult OffShelves()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="sBatchNO"></param>
        /// <param name="sGoodsCode"></param>
        /// <param name="sFlag"></param>
        /// <param name="checkTimeS"></param>
        /// <param name="checkTimeE"></param>
        /// <param name="cellNo"></param>
        /// <param name="sGoodsName"></param>
        /// <returns></returns>
        public JsonResult InitJsonResult(string sBatchNO, string sGoodsCode, string sFlag, string checkTimeS, string checkTimeE, string cellNo, string sGoodsName, string locationCode, string importBatchNo, string offshelvesType)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " where 1=1 and lg.status<>0 ";
            if (!string.IsNullOrEmpty(importBatchNo))
            {

                where += " and os.importBatchNo like'%" + importBatchNo + "%'";

            }
            else
            {
                if (!string.IsNullOrEmpty(sBatchNO))
                {
                    where += " and os.BatchNO like'%" + sBatchNO + "%'";
                }
                if (!string.IsNullOrEmpty(sGoodsCode))
                {
                    where += " and g.GOODSCODE like'%" + sGoodsCode + "%'";
                }
                if (!string.IsNullOrEmpty(sFlag))
                {
                    where += " and os.Flag =" + sFlag;
                }
                if (!string.IsNullOrEmpty(checkTimeS))
                {
                    where += " and os.OFFSHELVESDATE>= to_date('" + checkTimeS + "','yyyy-mm-dd hh24:mi:ss')";
                }
                if (!string.IsNullOrEmpty(checkTimeE))
                {
                    where += " and os.OFFSHELVESDATE<= to_date('" + checkTimeE + " 23:59','yyyy-mm-dd hh24:mi:ss')";
                }
                if (!string.IsNullOrEmpty(cellNo) && cellNo != "全部")
                {
                    where += " and l.CellNo ='" + cellNo + "'";
                }
                if (!string.IsNullOrEmpty(sGoodsName))
                {
                    where += " and g.GOODSNAME like'%" + sGoodsName + "%'";
                }
                if (!string.IsNullOrEmpty(locationCode))
                {
                    where += " and l.locationCode like'%" + locationCode + "%'";
                }
                if (!string.IsNullOrEmpty(offshelvesType) && offshelvesType!="-1")
                {
                    where += " and os.offshelvesType =" + offshelvesType;
                }
            }

            BOffShelves bi = new BOffShelves();
            var result = bi.GetOffShelvesList(page, rows, out total, where);

            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改or新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SaveData()
        {
            string sjson = string.Empty;
            try
            {
                AppUserList model = (AppUserList)Session["UserInfo"];

                string batchNo = Request["batchNo"];
                string txtGoodsCode = Request["txtGoodsCode"];
                string txtQTY = Request["txtQTY"];
                string txtRemark = Request["txtRemark"];
                string offShelvesDate = Request["offShelvesDate"];
                string hiddenOFFSHELVESID = Request["hiddenOFFSHELVESID"];

                OffShelves _OffShelves = new OffShelves();
                sjson = CheckOffShelves(hiddenOFFSHELVESID, batchNo, txtQTY, offShelvesDate, txtGoodsCode, txtRemark, "", "", out _OffShelves);
                if (!string.IsNullOrEmpty(sjson))
                {
                    return sjson;
                }
                else
                {
                    BOffShelves db = new BOffShelves();
                    int n = 0;
                    if (string.IsNullOrEmpty(hiddenOFFSHELVESID))
                    {
                        n = db.AddOffShelves(_OffShelves);
                        BAction action = new BAction();
                        ActionInfo ai = new ActionInfo();
                        ai.ACTIONTYPECODE = 4;
                        ai.OPERATION = "新增";
                        ai.OPCONTENT = "作业批次号:" + batchNo.ToString() + ",商品编码：" + _OffShelves.GOODSCODE + ",数量：" + _OffShelves.QTY.ToString();
                        ai.OPERATIONOLD = "";
                        ai.OPERATIONNEW = "";
                        ai.USERCODE = model.USERCODE;
                        action.AddLmActionInfo(ai);
                    }
                    else
                    {
                        _OffShelves.OFFSHELVESID = Convert.ToInt32(hiddenOFFSHELVESID);
                        n = db.UpdateOffShelvesByID(_OffShelves);
                        BAction action = new BAction();
                        ActionInfo ai = new ActionInfo();
                        ai.ACTIONTYPECODE = 4;
                        ai.OPERATION = "修改";
                        ai.OPCONTENT = "ID:" + hiddenOFFSHELVESID.ToString() + ",商品编码：" + _OffShelves.GOODSCODE + ",数量：" + _OffShelves.QTY.ToString();
                        ai.OPERATIONOLD = "";
                        ai.OPERATIONNEW = "";
                        ai.USERCODE = model.USERCODE;
                        action.AddLmActionInfo(ai);
                    }

                    if (n > 0)
                    {
                        sjson = "{success:true}";
                    }
                    else
                    {
                        sjson = "{success:false,msg:'添加失败.请联系管理员！'}";
                    }
                    return sjson;
                }
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;
        }

        /// <summary>
        /// 检测添加的数据
        /// </summary>
        /// <param name="OFFSHELVESID"></param>
        /// <param name="BatchNo"></param>
        /// <param name="QTY"></param>
        /// <param name="OffShelvesDate"></param>
        /// <param name="GoodsCode"></param>
        /// <param name="Remark"></param>
        /// <param name="offShelves"></param>
        /// <returns></returns>
        private string CheckOffShelves(string OFFSHELVESID, string BatchNo, string QTY, string OffShelvesDate, string GoodsCode, string Remark, string importBatchno, string replaceBatchNo, out OffShelves offShelves)
        {
            string sjson = string.Empty;
            AppUserList model = (AppUserList)Session["UserInfo"];
            offShelves = new OffShelves();
            offShelves.BATCHNO = BatchNo;
            decimal TQTY = 0;
            if (decimal.TryParse(QTY, out TQTY))
                offShelves.QTY = TQTY;
            DateTime dt = DateTime.Now;
            if (DateTime.TryParse(OffShelvesDate, out dt))
                offShelves.OFFSHELVESDATE = dt;
            offShelves.FLAG = "0";
            offShelves.REMARK = Remark;
            offShelves.CREATER = model.USERCODE;
            offShelves.CREATEDATE = DateTime.Now;
            offShelves.EDITOR = model.USERCODE;
            offShelves.EDITDATE = DateTime.Now;
            offShelves.IMPORTBATCHNO = importBatchno;
            offShelves.REPLACEBATCHNO = replaceBatchNo;
            BLocationGoods nbl = new BLocationGoods();
            List<Goods> checkgoods = nbl.CheckGoodsInfo(GoodsCode);
            if (checkgoods != null && checkgoods.Count > 0)
            {
                offShelves.GOODSID = checkgoods[0].GOODSID;
            }
            else
            {
                sjson = "{success:false,msg:'商品编码不存在！'}";
                return sjson;
            }
            BOffShelves nbs = new BOffShelves();
            List<OffShelves> lstOffShelves = nbs.CheckOffShelvesPrimary(offShelves.GOODSID, dt, BatchNo);
            if (lstOffShelves != null)
            {
                if (lstOffShelves.Where(_ => _.BATCHNO == BatchNo && _.OFFSHELVESID.ToString() != OFFSHELVESID).ToList().Count > 0)
                {
                    sjson = "{success:false,msg:'该指令已存在或者EXCEL中存在重复数据！'}";
                    return sjson;
                }
            }
            return sjson;
        }





        /// <summary>
        /// 导入指令下架
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string ImportOffshelvesInfo()
        {
            string sjson = string.Empty;
            try
            {
                HttpPostedFileBase file = Request.Files["files"];
                string importStr = string.Empty;
                DataTable table = new DataTable();
                sjson = ImportFile(file, out table, out importStr);
                if (!string.IsNullOrEmpty(sjson))
                {
                    return sjson;
                }
                TransactionOptions transactionOption = new TransactionOptions();

                //设置事务隔离级别
                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

                // 设置事务超时时间为600秒
                transactionOption.Timeout = new TimeSpan(0, 0, 600);

                //引用事务机制，出错时，事物回滚
                using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transactionOption))
                {

                    BOffShelves db = new BOffShelves();
                    AppUserList model = (AppUserList)Session["UserInfo"];
                    string batchno = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();


                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        OffShelves ol = new OffShelves();
                        if (table.Rows[i][0] != null && table.Rows[i][0].ToString().Trim() != "")
                        {
                            string sd = table.Rows[i][4].ToString();
                            sjson = CheckOffShelves("", table.Rows[i][0].ToString().Trim(), table.Rows[i][2].ToString().Trim(), table.Rows[i][3].ToString().Trim(), table.Rows[i][1].ToString().Trim(), "人工导入", batchno, table.Rows[i][4].ToString().Trim(), out ol);
                            if (!string.IsNullOrEmpty(sjson))
                            {
                                return sjson;
                            }
                            else
                            {
                                ol.OFFSHELVESTYPE = 1;//类型为导入
                                int bl = db.AddOffShelves(ol);

                            }

                        }

                    }
                    sjson = "{success:true,batch:'" + batchno + "'}";
                    transaction.Complete();
                }
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            System.Threading.Thread.Sleep(2000);
            return sjson;
        }


        [HttpPost]
        public string Delete()
        {
            string sjson = string.Empty;
            try
            {
                string ids = Request["hiddenIDlist"];
                if (!string.IsNullOrEmpty(ids))
                {
                    AppUserList model = (AppUserList)Session["UserInfo"];
                    if (ids != null && ids != "")
                    {
                        ids = ids.Substring(0, ids.Length - 1);

                    }
                    int n = 0;
                    BOffShelves db = new BOffShelves();
                    foreach (var id in ids.Split(','))
                    {
                        n = db.DeleteOffShelves(int.Parse(id));
                    }

                    if (n > 0)
                    {
                        sjson = "{success:true}";
                    }
                    else
                    {
                        sjson = "{success:false,msg:'修改失败!'}";
                    }
                }
                else
                {
                    sjson = "{success:false,msg:'请选择要删除的项!'}";
                }

            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;

        }

        /// <summary>
        /// 按照批次号删除指令
        /// </summary>
        /// <returns></returns>
        public string DeleteBatch()
        {
            string sjson = string.Empty;
            try
            {
                string importBatch = Request["txtOffShelvesBatch"];
                if (!string.IsNullOrEmpty(importBatch))
                {

                    BOffShelves db = new BOffShelves();
                    List<OffShelves> list = db.CheckOffShelvesStatus(importBatch);
                    if (list != null && list.Count > 0)
                    {
                        sjson = "{success:false,msg:'要删除的指令批次中存在非未处理的指令!'}";
                    }
                    else
                    {
                        int n = db.DeleteOffShelvesByImportBatch(importBatch);

                        if (n > 0)
                        {
                            sjson = "{success:true}";
                        }
                        else
                        {
                            sjson = "{success:false,msg:'删除失败,请检查批次号是否正确!'}";
                        }
                    }

                }
                else
                {
                    sjson = "{success:false,msg:'请填写要删除的批次号!'}";
                }

            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;

        }
    }
}
